package cc.fathervideoplayer

import android.app.Activity
import android.net.Uri
import android.os.Bundle
import android.view.View
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.ui.PlayerView


class PlayActivity : Activity() {
    private var bookmark = 0L
    private var path = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_play)
        path = intent.getStringExtra("path").toString()
        if (path.isNullOrEmpty()) {
            finish()
            return
        }
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        initializePlayer()
        window.decorView.keepScreenOn = true
        bookmark = mmkv.decodeLong(path, 0)
        playChannel(path)
        findViewById<View>(R.id.icBack).setOnClickListener {
            onBackPressed()
        }
    }

    private lateinit var player: ExoPlayer

    private fun initializePlayer() {
        player = ExoPlayer.Builder(this).build()
        val playerView: PlayerView = findViewById(R.id.player)
        playerView.player = player
        playerView.useController = true // 根据需求启用或禁用控制器
    }

    override fun onPause() {
        super.onPause()
        player.pause()
        mmkv.encode(path, player.currentPosition)
    }

    override fun onResume() {
        super.onResume()
        if (!player.isPlaying) {
            player.play()
        }
    }

    private fun playChannel(channelUrl: String) {
        val videoUri = Uri.parse(channelUrl)
        val mediaItem = MediaItem.fromUri(videoUri)
        player.setMediaItem(mediaItem)
        player.prepare()
        player.play()
        if (bookmark > 0) {
            player.seekTo(bookmark)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mmkv.encode(path, player.currentPosition)
        player?.stop()
        player?.release()
    }
}
